#!/usr/bash/bin
INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/jdk"
fi

##JDK架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/jdk/jdk1.8/jdk1.8.0_131/jdk-8u131-linux-x64.tar.gz
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/jdk/jdk1.8/jdk1.8.0_131/jdk-8u131-linux-x64.tar.gz"
fi

##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#截取文件名
#NAME_ARRAY=(${FILENAME//-/ });
#重新定义文件名
#NEW_FILENAME=${NAME_ARRAY[0]}_${NAME_ARRAY[1]};

#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH/$NEW_FILENAME ];then
   mkdir $INSTALL_PATH
#  mkdir $INSTALL_PATH/$NEW_FILENAME
fi

cd $INSTALL_PATH 

#wget下载文件
wget $DOWNLOAD_URL

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
        tar -zxvf $FILENAME -C $INSTALL_PATH
    else
        unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
fi


#删除JDK安装包
rm -rf $INSTALL_PATH/$FILENAME

#获取解压后当前目录下的文件名
#NEW_FILENAME=`ls -lt /usr/local/jdk|grep jdk|head -n 1|awk '{print $9}'`;
DIR_ARRY=$(ls -l $INSTALL_PATH |awk '/^d/ {print $NF}')
NEW_FILENAME=${DIR_ARRY[0]}

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi

cat >>/etc/profile<<EOF
export JAVA_HOME=$INSTALL_PATH/$NEW_FILENAME
export JRE_HOME=\$JAVA_HOME/jre
export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib/tools.jar
export PATH=\$PATH:\$JAVA_HOME/bin
EOF

#重启/ect/profile环境
source /etc/profile

#验证是否安装jdk完毕
java -version

if [ $? -ne 0 ]; then
    echo "JDK安装失败,已自动退出脚本，请自行请排查原因!!!"
else
    echo "JDK安装成功，退出脚本!!!"
fi


